/**
 * 
 */
package cn.com.xf.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.FrameworkServlet;

import cn.com.xf.common.Constants;

/**
 * @author fangjinsong flash上传专用，上传到临时文件 /servlet/upload
 * 
 */
public class FileUploadServlet extends HttpServlet {
	static HashMap<String, String> extMap = new HashMap<String, String>();
	static {
		// extMap.put("image", "gif,jpg,jpeg,png,bmp");
		// extMap.put("flash", "swf,flv");
		// extMap.put("media",
		// "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		extMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,txt,pdf,zip,rar,jpg,mp4,f4v,flv,apk,exe");
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String error = "0";
		String errorMessage = "";
		String fileId = "";
		// 1.查找web应用上下文
		ApplicationContext wac = null;
		Object acObject = getServletConfig().getServletContext().getAttribute(getSrpingWebContentAttributeName());
		if (acObject instanceof ApplicationContext) {
			wac = (ApplicationContext) acObject;
		}
		if (wac == null) {
			return;
		}
		CommonsMultipartResolver multipartResolover = (CommonsMultipartResolver) wac.getBean("multipartResolver");
		// 2.分析上传的文件
		MultipartHttpServletRequest multipartRequest = checkMultipart(req, multipartResolover);
		if (multipartRequest == null) {
			return;
		}
		Map<String, MultipartFile> maps = multipartRequest.getFileMap();
		int num = 0;
		for (Map.Entry<String, MultipartFile> m : maps.entrySet()) {
			// 目前只取第一个文件
			if (num > 0) {
				break;
			}
			try {
				MultipartFile mf = m.getValue();
				boolean isCorrectFile = checkFileType(mf.getOriginalFilename());
				if (!isCorrectFile) {
					error = "1";
					errorMessage = "文件格式不正确";
				} else {
					// 保存文件到临时文件
					String prepath = req.getSession().getServletContext().getRealPath("/");
					fileId = UUID.randomUUID() + "";
					String tempFileName = fileId + Constants.UPLOAD_TEMP_SPILT + mf.getOriginalFilename();
					String savePath = prepath + Constants.UPLOAD_PATH_TEMP;
					File saveFile = new File(savePath, tempFileName);
					mf.transferTo(saveFile);
				}
				num++;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (multipartRequest instanceof MultipartHttpServletRequest) {
			multipartResolover.cleanupMultipart(multipartRequest);
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("status", error);
		map.put("errorMessage", errorMessage);
		map.put("fileId", fileId);
		String s = org.json.simple.JSONObject.toJSONString(map);
		resp.getWriter().println(s);
	}

	private String getSrpingWebContentAttributeName() {
		return FrameworkServlet.class.getName() + ".CONTEXT." + "oa";
	}

	private MultipartHttpServletRequest checkMultipart(HttpServletRequest request,
			CommonsMultipartResolver multipartResolver) {
		MultipartHttpServletRequest multipartRequest = null;
		if (multipartResolver != null && multipartResolver.isMultipart(request)) {
			if (request instanceof MultipartHttpServletRequest) {

			} else {
				try {
					multipartRequest = multipartResolver.resolveMultipart(request);
				} catch (MultipartException e) {
					e.printStackTrace();
				}
			}
		}
		return multipartRequest;
	}

	/**
	 * 检查文件名后缀
	 * 
	 * @param fileName
	 * @return
	 */
	private boolean checkFileType(String fileName) {
		if (fileName.contains(".")) {
			int last = fileName.lastIndexOf(".");
			String fileType = fileName.substring(last + 1, fileName.length());
			if (Arrays.<String> asList(extMap.get("file").split(",")).contains(fileType.toLowerCase())) {
				return true;
			}
		}
		return false;
	}
}
